const mongoose = require('mongoose')
const bcrypt = require('bcrypt-nodejs')
const jwt = require('jsonwebtoken')
const User = mongoose.model('user')
const config = require('../config')
const { formatBody } = require('../tools')
const sendMail = require('../tools/mailer')

module.exports = {
  async registerCode (ctx) {
    let { email } = ctx.request.body
    let Reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
    if (!email || !Reg.test(email)) {
      return ctx.body = formatBody(0, '请填写合法的邮箱')
    }
    let signCode = ''
    for (let i = 0; i < 6; i++) {
      signCode += Math.floor(Math.random() * 10)
    }
    ctx.session.signCode = signCode
    ctx.session.signCodeExp = Date.now() + 1000 * 60 * 5
    await sendMail({
      to: [
        email
      ],
      subject: '验证码',
      text: `您的验证码为：${signCode}。请不要把验证码泄露给其他人！5分钟内有效。`
    }).then(info => {
      return ctx.body = formatBody(1, '获取成功', info)
    }).catch(err => {
      return ctx.body = formatBody(0, '获取验证码失败', err)
    })
  },
  async register (ctx) {
    let { nickname, email, password, signCode } = ctx.request.body
    if (!nickname || !email || !password) {
      return ctx.body = formatBody(0, '昵称，邮箱，密码都不可为空')
    }
    if (signCode != ctx.session.signCode) {
      return ctx.body = formatBody(0, '验证码错误')
    }
    if (ctx.session.signCodeExp - Date.now() > 1000 * 60 * 5) {
      return ctx.body = formatBody(0, '验证码已失效，请重新获取')
    }
    let repemail = await User.find({ email: email })
    if (repemail.length) {
      return ctx.body = formatBody(0, '此邮箱已经被注册')
    }
    // password加盐
    password = bcrypt.hashSync(password, bcrypt.genSaltSync(10))
    // 新建该用户实例
    let user = new User ({ nickname, email, password })
    await user.save()
    return ctx.body = formatBody(1, '注册成功')
  },
  async login (ctx) {
    let { email, password } = ctx.request.body
    let user = await User.findOne({
      email: email
    }).populate({
      path: 'vip',
      select: '_id type activationDate expireDate createAt'
    })
    if (!user) return ctx.body = formatBody(0, '不存在该用户')
    if (!password) return ctx.body = formatBody(0, '密码不可为空')
    if(bcrypt.compareSync( password, user.password)) {
      // 最后一次登录时间
      user.lastOnline = new Date()
      user.save()
      // 生成token返回给客户端
      let exp = Math.floor((new Date().getTime())/1000) + 60 * 60 * 24 * 30
      let token = await jwt.sign({ user_id: user._id, exp }, config.server.SIGN_KEY )
      delete user.password
      return ctx.body = formatBody(1, '登陆成功', { token, user })
    }
    return ctx.body = formatBody(0, '密码错误')
  },
  // 获取用户信息
  async userInfo (ctx) {
    let { _id } = ctx.request.body
    if (!_id) return ctx.body = formatBody(0, '没有用户id，0.0！')
    const user = await User.findOne({ _id: _id }, { password: 0 }).populate({
      path: 'vip',
      select: '_id activationDate expireDate createAt',
      populate: {
        path: 'type',
        select: 'type validDay desc'
      }
    })
    if(user) {
      return ctx.body = formatBody(1, 'ok', user)
    }
    return ctx.body = formatBody(0, '不存在此用户')
  },
  async total (ctx) {
    let total = await User.countDocuments()
    return ctx.body = formatBody(1, 'ok', { total })
  },
  async list (ctx) {
    let page = ctx.query.page || 1
    let limit = ctx.query.limit || 20
    let keyword = ctx.query.keyword || ''
    let list = await User.find({
        nickname: { $regex: keyword, $options: '$i' }
      }, { nickname: 1, email: 1, createAt: 1 })
      .populate({
        path: 'vip',
        select: 'type activationDate expireDate createAt'
      })
      .sort({ 'meta.updatedAt': -1 })
      .limit(+limit).skip(+limit * (+page - 1))
    let total = await User.countDocuments()
    return ctx.body = formatBody(1, 'ok', { total, list })
  },
  async disconnect (info, socket, io) {
    // let online = await Socket.findOne({
    //   socket_id: socket.id
    // }).populate({
    //   path: 'user',
    //   select: '_id nickname matchState matchUser'
    // })
    // if (online) {
    //   await User.update({
    //     _id: online.user._id
    //   }, {
    //     $set: {
    //       matchState: 1,
    //       matchUser: null,
    //       onlineState: false,
    //       lastOnline: new Date()
    //     }
    //   })
    //   if (online.user.matchState === 3) {
    //     // 通知当前匹配对象 我已经离开
    //     let matchUser = await User.findOne({
    //       _id: online.user.matchUser
    //     }).populate('socket','socket_id')

    //     await User.update({
    //       _id: online.user.matchUser
    //     }, {
    //       $set: {
    //         matchState: 1,
    //         matchUser: null
    //       }
    //     })

    //     io.to(matchUser.socket.socket_id).emit('random chat', {
    //       id: online.user._id,
    //       type: 'leave'
    //     })
    //     console.log(99999)
    //   }
    //   await Socket.remove({socket_id: socket.id})

    //   socket.broadcast.emit('offline',{_id: online.user._id, nickname: online.user.nickname})
    //   console.log(`--------------------${online.user.nickname}下线了`);
    // }
  }
}